<?php

    class BillController extends AdminController
    {
        public function init(){
            parent::init();
            $this->menu_parent_selected = 'bill';

        }

        /**
        * @return array action filters
        */
        public function filters()
        {
            return array(
                'accessControl', // perform access control for CRUD operations
                'postOnly + delete', // we only allow deletion via POST request
            );
        }

        /**
        * Specifies the access control rules.
        * This method is used by the 'accessControl' filter.
        * @return array access control rules
        */
        public function accessRules()
        {
            return array(
                array('allow',
                    'actions'=>array('view'),
                    'users'=>array('*'),
                ),
                array('allow', // allow authenticated user to perform 'create' and 'update' actions
                    'actions'=>array('create', 'index', 'delete', 'update', 'ajaxSuggestCustomerByPhone', 'ajaxSuggestCustomerByName', 'ajaxGetCustomerPoint', 'paylist', 'paylistView', 'paylistCreate','ajaxLoadPaylistBills'),
                    'users'=>array('@'),
                ),
                array('deny',  // deny all users
                    'users'=>array('*'),
                ),
            );
        }

        public function actionIndex()
        {
            $this->menu_child_selected = 'bill';
            $this->menu_sub_selected = 'index';

            $model = new Bill('search');
            $model->unsetAttributes();  // clear any default values
            if(isset($_GET['Bill'])){
                $model->attributes=$_GET['Bill'];
                if(!empty($_GET['Bill']['customer_phone'])) $model->customer_phone = $_GET['Bill']['customer_phone'];     
                if(!empty($_GET['Bill']['customer_name'])) $model->customer_name = $_GET['Bill']['customer_name'];     
            }


            $criteria=new CDbCriteria;
            $criteria->with = array('customer' => array(
                'alias' => 'c',
                'select' => 'phone, name, address',
            ));
            $criteria->together = true;

            $sort = Yii::app()->request->getQuery('Bill_sort');

            if(!$sort && $sort != 'created') $criteria->order = 't.created DESC'; 
            $criteria->compare('t.code',$model->code, true);
            $criteria->compare('t.type',$model->type);
            $criteria->compare('c.phone',$model->customer_phone,true);
            $criteria->compare('c.name',$model->customer_name,true);
            $criteria->compare('t.branch_id',$model->branch_id);
            $criteria->compare('t.manager_id',$model->manager_id);
            $criteria->compare('t.created',$model->created,true);
            $criteria->compare('t.status_pay',$model->status_pay);
            $criteria->compare('t.status_do',$model->status_do);
            $criteria->compare('t.status_return',$model->status_return);
            $criteria->compare('t.status',$model->status);

            $dataProvider = new CActiveDataProvider($model, array(
                'criteria'=>$criteria,
                'pagination'=>array(
                    'pageSize'=>20,
                ),
            ));



            $branch_id = $model->branch_id;
            if(count(Branch::model()->branchData) == 1){
                $branch_id = key(Branch::model()->getBranchData());
            }


            $managers = Manager::model()->with(array(
                'branches' => array(
                    'condition' => 'branches.id = :branch_id AND branches.status = "ENABLE"',
                    'params' => array(':branch_id' => $branch_id),
                )
            ))->findAll("t.`status` != :status", array(':status' => 'DISABLE'));
            $managerData = CHtml::listData($managers, 'id', 'name');

            $this->render('index',array(
                'model'         =>  $model,
                'dataProvider'         =>  $dataProvider,
                'managerData'         =>  $managerData,
            ));
        }

        public function actionAjaxLoadPaylistBills(){
            $dateFrom = Yii::app()->request->getPost('date_from');
            $dateTo = Yii::app()->request->getPost('date_to');

            $bills = Bill::model()->findAll(array(
                'condition' => "`type` = 'ITEM' AND item_paid = 0 AND `status` = 'COMPLETED' AND created BETWEEN '{$dateFrom}' AND '{$dateTo}'",
            ));


            $this->renderPartial('ajax_load_paylist_bills', compact('bills'));

        }

        public function actionPaylistCreate(){
            $this->menu_child_selected = 'bill_paylist_create';
            $this->menu_sub_selected = 'bill_paylist_create';
            $model = new Paylist;


            if($post = Yii::app()->request->getPost('Paylist')){

                $model->attributes = $post;
                $model->manager_id = $this->manager->id;
                $model->created = MyDateTime::getCurrentTime();

                if($model->validate()){
                    $model->insert();

                    $criteria = new CDbCriteria();
                    $criteria->addInCondition('id', $_POST['bill']); 
                    Bill::model()->updateAll(array('item_paid' => 1), $criteria);

                    foreach($_POST['bill'] as $bill_id){
                        $phb = new PaylistHasBill;
                        $phb->paylist_id = $model->id;
                        $phb->bill_id = $bill_id;
                        $phb->insert();
                    }

                    Yii::app()->user->setFlash('success', "Paylist đã được tạo thành công.");
                    //$this->refresh();
                    $this->redirect($model->getUrl('view'));
                }
            }

            $this->render('paylist_create',array(
                'model'         =>  $model,
            ));
        }

        public function actionPaylist(){
            $this->menu_child_selected = 'bill_paylist';
            $this->menu_sub_selected = 'bill_paylist';

            $model = new Paylist('search');
            $model->unsetAttributes();
            if(isset($_GET['Paylist'])){
                $model->attributes=$_GET['Paylist'];
            }

            $criteria=new CDbCriteria;
            $dataProvider = new CActiveDataProvider($model, array(
                'criteria'=>$criteria,
                'pagination'=>array(
                    'pageSize'=>20,
                ),
            ));

            $this->render('paylist_index',array(
                'model'         =>  $model,
                'dataProvider'         =>  $dataProvider,
            ));
        }

        public function actionPaylistView($id){
            $this->menu_child_selected = 'bill_paylist_view';
            $this->menu_sub_selected = 'bill_paylist_view';
            $model = Paylist::model()->findByPk($id);

            $this->render('paylist_view',array(
                'model'         =>  $model,
            ));
        }
        
        public function actionAjaxGetCustomerPoint($phone = 0){
            $customer = Customer::model()->findByAttributes(array('phone' => $phone));
            echo $customer ? json_encode($customer->attributes) : json_encode(false);
        }

        public function actionAjaxSuggestCustomerByPhone($term)
        {
            $data = array();

            $qtxt = "SELECT id, `name`, phone, address FROM customer WHERE phone LIKE :phone LIMIT 10";
            $command = Yii::app()->db->createCommand($qtxt);
            $command->bindValue(":phone", '%'.$term.'%', PDO::PARAM_STR);
            $dataReader = $command->query();
            while($row = $dataReader->read()){
                $data[] = array(
                    'label' => "{$row['phone']} - {$row['name']}",
                    'value' => $row['phone'],
                    'name' => $row['name'],
                    'address' => $row['address'],
                );
            }

            echo json_encode($data);
            Yii::app()->end();
        }

        public function actionAjaxSuggestCustomerByName($term)
        {
            $data = array();

            $qtxt = "SELECT id, `name`, phone, address FROM customer WHERE `name` LIKE :name LIMIT 10";
            $command = Yii::app()->db->createCommand($qtxt);
            $command->bindValue(":name", '%'.$term.'%', PDO::PARAM_STR);
            $dataReader = $command->query();
            while($row = $dataReader->read()){
                $data[] = array(
                    'label' => "{$row['phone']} - {$row['name']}",
                    'value' => $row['name'],
                    'phone' => $row['phone'],
                    'address' => $row['address'],
                );
            }

            echo json_encode($data);
            Yii::app()->end();
        }

        /**
        * Creates a new model.
        * If creation is successful, the browser will be redirected to the 'view' page.
        */
        public function actionCreate()
        {   
            //                        echo '<pre>';print_r(Item::model()->itemDataArray);echo '</pre>';die;
            $this->menu_child_selected = 'bill_create';
            $this->menu_sub_selected = 'create';

            $branches = $this->manager->branches(array('condition' => 'branches.`status` = "ENABLE"'));
            if(!$branches) $branches = Branch::model()->findAllByAttributes(array('status' => 'ENABLE'));

            if(isset($_POST['customer_phone'])){


                $post = $_POST;
                //                echo '<pre>';print_r($post);echo '</pre>';die;
                // su dung nhung dich vu nao
                $use_service = $post['use_service'];  

                // check error
                if($post['customer_phone'] != 0 && !preg_match('/^0\d{9,10}$/', $post['customer_phone'])){
                    Yii::app()->user->setFlash('error', $this->t('Số điện thoại khách hàng không hợp lệ'));
                    $this->refresh();
                }
                if(strlen($post['customer_name']) < 4){
                    Yii::app()->user->setFlash('error', $this->t('Tên khách hàng phải được điền và không quá ngắn'));
                    $this->refresh();
                } 
                // giat kho phai la don hang rieng biet
                if(in_array('laundry_dry', $use_service) && count($use_service) > 1){
                    Yii::app()->user->setFlash('error', $this->t('Dịch vụ giặt khô phải là đơn hàng riêng biệt'));
                    $this->refresh();
                } 
                if(!in_array($post['status_pay'], array('PAID', 'UNPAID'))){
                    Yii::app()->user->setFlash('error', $this->t('Trạng thái thanh toán không hợp lệ'));
                    $this->refresh();
                } 



                // item list
                $items = array();
                if(isset($post['item_name'])){
                    foreach($post['item_name'] as $i => $v){

                        if(!$post['item_name'][$i]) continue;

                        $item = array(
                            'id'  =>  $post['item_name'][$i],
                            'group'  =>  $post['item_group'][$i],
                            'gender'  =>  $post['item_gender'][$i],
                            'color'  =>  $post['item_color'][$i],
                            'more_info'  =>  $post['item_more_info'][$i],
                        );

                        if(in_array('laundry', $use_service)) $item['laundry_price']  =  $post['laundry_price'][$i];
                        if(in_array('dry', $use_service)) $item['dry_price']  =  $post['dry_price'][$i];
                        if(in_array('iron', $use_service)) $item['iron_price']  =  $post['iron_price'][$i];
                        if(in_array('laundry_dry', $use_service)) $item['laundry_dry_price']  =  $post['laundry_dry_price'][$i];

                        $items[] = $item;  
                    }
                }

                if(!$items){
                    Yii::app()->user->setFlash('error', $this->t('Đơn hàng phải có đồ giặt'));
                    $this->refresh();
                } 

                // each service prices
                $prices = array(
                    'laundry_price' => 0,
                    'dry_price' => 0,
                    'iron_price' => 0,
                    'laundry_dry_price' => 0,
                );

                foreach($items as $item){
                    if(isset($item['laundry_price']))       $prices['laundry_price'] += $item['laundry_price'];
                    if(isset($item['dry_price']))           $prices['dry_price'] += $item['dry_price'];
                    if(isset($item['iron_price']))          $prices['iron_price'] += $item['iron_price'];
                    if(isset($item['laundry_dry_price']))   $prices['laundry_dry_price'] += $item['laundry_dry_price'];
                }

                //                if($post['bill_type'] == 'PACKAGE'){
                //                    if(in_array('laundry', $use_service)) $prices['laundry_price'] = Item::model()->price_package_laundry;
                //                    if(in_array('dry', $use_service)) $prices['dry_price'] = Item::model()->price_package_dry;
                //                }

                $price = array_sum($prices);
                $price_laundry_dry = $prices['laundry_price'] + $prices['dry_price'];
                $used_point = empty($post['used_point']) ? 0 : $post['used_point'];
                $pay_price  = $price - $used_point;
                $pay_price_laundry_dry  = $price_laundry_dry - $used_point;


                $newPassword = null;

                // update & create customer 
                $customer = Customer::model()->findByAttributes(array('phone' => $post['customer_phone']));
                if(!$customer){
                    $customer = new Customer;
                    $customer->setIsNewRecord(TRUE);

                    $newPassword = $customer->getNewPassword();
                    $customer->password = $customer->getHashPassword($newPassword);
                    $customer->created = MyDateTime::getCurrentTime();
                }
                else{
                    $customer->setIsNewRecord(FALSE);
                }
                $customer->attributes = array(
                    'phone' => $post['customer_phone'],
                    'name' => $post['customer_name'],
                    'address' => $post['customer_address'],
                );
                $customer->save();



                // check error : kiem tra neu su dung diem thuong
                if($used_point){

                    if($post['bill_type'] == 'ITEM'){
                        Yii::app()->user->setFlash('error', $this->t("Điểm thưởng chỉ được sử dụng cho đơn hàng (giặt theo lượt): giặt ướt, sấy khô"));
                        $this->refresh();
                    }
                    elseif($customer->point < Yii::app()->params->point_use_min){
                        Yii::app()->user->setFlash('error', $this->t("Không thể sử dụng điểm để thanh toán. Số điểm hiện tại của khách hàng {$customer->point} < ".Yii::app()->params->point_use_min."k."));
                        $this->refresh();
                    }
                    elseif($used_point > $customer->point){
                        Yii::app()->user->setFlash('error', $this->t("Không thể sử dụng điểm để thanh toán. Số điểm khách hàng dùng nhiều hơn số điểm có: {$used_point} > {$customer->point}"));
                        $this->refresh();
                    }
                    elseif($pay_price_laundry_dry < 0){
                        Yii::app()->user->setFlash('error', $this->t("Không thể sử dụng điểm để thanh toán. Số điểm khách hàng dùng nhiều hơn tổng tiền của đơn hàng: {$used_point} > {$price}"));
                        $this->refresh();
                    }

                    $customer->point = $customer->point - $used_point; 
                    $customer->save();   
                }

                $customer_point_before = $customer->point;
                $customer_point_after = $customer->point;
                $bonus_point = 0;
                $bonus_percent = Yii::app()->params->bonus_percent;

                // chỉ tặng điểm cho dịch vụ: giặt ướt, sấy khô
                if($post['bill_type'] == 'PACKAGE'){
                    $bonus_point = round($pay_price_laundry_dry*$bonus_percent/100);
                    $customer_point_after = $customer->point - $used_point + $bonus_point;
                } 


                $info = array(
                    'prices' => $prices,
                    'items' => $items,
                );


                $bill = new Bill;
                $bill->code = $bill->getNextCode();
                $bill->customer_id = $customer->id;
                $bill->customer_guest_name = $customer->id == 1 ? $post['customer_name'] : NULL;
                $bill->customer_guest_address = $customer->id == 1 ? $post['customer_address']: NULL;
                $bill->type          = $post['bill_type'];
                $bill->use_service_laundry          = in_array('laundry', $use_service) ? 1: 0;
                $bill->use_service_dry          = in_array('dry', $use_service) ? 1: 0;
                $bill->use_service_iron          = in_array('iron', $use_service) ? 1: 0;
                $bill->use_service_laundry_dry          = in_array('laundry_dry', $use_service) ? 1: 0;
                $bill->price = $price;
                $bill->used_point = $used_point;
                $bill->pay_price = $pay_price;
                $bill->pay_price_laundry_dry = $pay_price_laundry_dry;
                $bill->bonus_percent = $bonus_percent;
                $bill->bonus_point = $bonus_point;
                $bill->add_customer_point = 0;
                $bill->customer_point_before = $customer_point_before;
                $bill->customer_point_after = $customer_point_after;
                $bill->branch_id = $post['branch_id'];
                $bill->manager_id = $this->manager->id;
                $bill->created = MyDateTime::getCurrentTime();
                $bill->status_pay = $post['status_pay'];
                $bill->status_do = 'PENDING';
                $bill->status_return = 'NO';
                $bill->status = "PROCESSING";
                $bill->info  = json_encode($info);
                $bill->setIsNewRecord(TRUE);
                $bill->insert();


                $mub = new ManagerUpdateBill;
                $mub->bill_id = $bill->id;
                $mub->status_pay = $bill->status_pay;
                $mub->status_do = $bill->status_do;
                $mub->status_return = $bill->status_return;
                $mub->status = $bill->status;
                $mub->manager_id = $bill->manager_id;
                $mub->created = $bill->created;
                $mub->setIsNewRecord(TRUE);
                $mub->insert();

                // send password to new customer
                if($customer->phone && $newPassword){
                    $msg = "GiatLaVui.com: Cam on ban da su dung dich vu cua Giat La Vui. Tai khoan cua ban da duoc tao voi so dien thoai: {$customer->phone}, mat khau: {$newPassword}";
                    Yii::app()->sms->send($customer->phone, $msg, $bill->id, $this->manager->id); 
                }

                Yii::app()->user->setFlash('success', "<strong>Thành công!</strong> đơn hàng đã được tạo với mã <b>{$bill->code}</b>");

                $this->redirect($bill->adminUrl);

            }

            $this->pageTitle = $this->t('Tạo đơn hàng').' | '.$this->siteName;
            $this->render('create', compact('branches'));
        }

        public function actionUpdate($code)
        {
            $this->menu_child_selected = 'bill';
            $this->menu_sub_selected = 'update';

            $model=$this->loadModel($code);
            $model->scenario = 'update';

            if(isset($_POST['ajax']) && $_POST['ajax']==='bill-form'){
                echo CActiveForm::validate($model);
                Yii::app()->end();
            }


            $add_customer_point_before = $model->add_customer_point;

            if(isset($_POST['Bill']))
            {
                $model->attributes=$_POST['Bill'];

                if($model->validate()){

                    $customer = $model->customer;

                    // update point
                    if($model->bonus_point){


                        if($customer->phone && $model->bonus_point){
                            // add customer point 
                            if($model->status == 'COMPLETED' && !$model->add_customer_point){
                                $customer->point += $model->bonus_point;
                                $customer->setIsNewRecord(false);
                                $customer->update(); 

                                $model->add_customer_point = 1;
                            }
                            // sub customer point
                            elseif($model->status != 'COMPLETED' && $model->add_customer_point){
                                $customer->point -= $model->bonus_point;
                                $customer->setIsNewRecord(false);
                                $customer->update();

                                $model->add_customer_point = 0;
                            } 
                        }
                    }

                    //update completed time
                    if($model->status_do == 'COMPLETED'){
                        $model->completed = MyDateTime::getCurrentTime();

                        // send sms
                        if(!$model->sms_sent && $customer->is_receive_sms){
                            $msg = "";
                            if($model->bonus_point && $model->status_pay == 'PAID'){
                                $msg = "Diem tich luy them: {$model->bonus_point}k.";    
                            }

                            if($customer->point){
                                $msg .= "Tong diem: {$customer->point}.";
                            }

                            $msg = "GiatLaVui.com: Xin chao {$customer->nameAlias}. Don hang {$model->code} cua ban da giat xong, moi ban ra lay do. {$msg}";

                            if($model->send_sms){
                                Yii::app()->sms->send($customer->phone, $msg, $model->id, $this->manager->id); 
                                $model->sms_sent = MyDateTime::getCurrentTime(); 
                            } 
                        }


                    }else{
                        $model->completed = NULL;
                    }

                    $model->update();


                    $mub = new ManagerUpdateBill;
                    $mub->bill_id = $model->id;
                    $mub->status_pay = $model->status_pay;
                    $mub->status_do = $model->status_do;
                    $mub->status_return = $model->status_return;
                    $mub->status = $model->status;
                    $mub->manager_id = $this->manager->id;
                    $mub->created = MyDateTime::getCurrentTime();
                    $mub->setIsNewRecord(TRUE);
                    $mub->insert();

                    Yii::app()->user->setFlash('success', 'Cập nhật đơn hàng thành công.');

                    $this->refresh();
                }               
            }

            $info = json_decode($model->info, true);

            Item::model()->formatInfo($info);

            $this->render('update',array(
                'model'=>$model,
                'info' => $info,
            ));
        }


        /**
        * Returns the data model based on the primary key given in the GET variable.
        * If the data model is not found, an HTTP exception will be raised.
        * @param integer the ID of the model to be loaded
        */
        public function loadModel($code)
        {
            $model=Bill::model()->findByAttributes(array('code' => $code));
            if($model===null)
                throw new CHttpException(404,'The requested page does not exist.');
            return $model;
        }

    }
